from django.shortcuts import render
from django.views import View
from django.http import HttpResponse
from utils.pageTool import get_objects_page
from .models import *

def wrapper_recommend_goods_cookie(func):
    def _wrapper(detailview, request, goods_id, *args, **kwargs):
        raw_commend_goods = request.COOKIES.get('recommend_goods', '')
        commend_goods = [item for item in raw_commend_goods.split() if item.strip()]
        recommend_goods = [Goods.objects.get(id=gid) for gid in commend_goods if int(gid) != goods_id and
                           Goods.objects.get(id=gid).category_id == Goods.objects.get(id=goods_id).category_id][:4]
        response = func(detailview, request, goods_id, recommend_goods, *args, **kwargs)
        goods_id = str(goods_id)
        if goods_id not in commend_goods:
            commend_goods.append(goods_id)
        else:
            commend_goods.remove(goods_id)
            commend_goods.insert(0, goods_id)

        response.set_cookie('recommend_goods', ' '.join(commend_goods), max_age=60*60*24*3)
        return response
    return _wrapper



# Create your views here.

class TestViews(View):

    def get(self, request, pagenum=1):
        object_list = Goods.objects.all()
        page, goodses = get_objects_page(object_list, pagenum, 5)
        page_range = page.paginator.page_range
        return render(request, 'test.html', {'goodses': goodses, 'page_range': page_range})


class IndexViews(View):
    categorys = Category.objects.all()
    current_categoryid = Category.objects.first().id

    def get(self, request, category_id=None, pagenum=1):
        if category_id == None:
            current_cid = self.current_categoryid
        else:
            current_cid = category_id

        pages, goods = get_objects_page(Goods.objects.filter(category_id=current_cid), pagenum)
        return render(request, 'index.html', {'categorys': self.categorys, 'current_cid': int(current_cid), 'goods': goods, 'pages': pages})


class DetailsViews(View):
    @wrapper_recommend_goods_cookie
    def get(self, request, goods_id, recommend_goods=[]):
        goods = Goods.objects.get(id=int(goods_id))
        return render(request, 'detail.html', {'goods': goods,'recommend_goods': recommend_goods})